from datetime import datetime
from datetime import timedelta
from industrialai.pkg import const
import jwt
import os

const.jwtKey = "jwt_key"
const.defaultKey = "SECRET_KEY"


class JWT(object):
    def createToken(userId, roleId):
        payload = {
            'exp': int((datetime.now() + timedelta(minutes=30)).timestamp()),
            'userId': userId,
            'roleId': roleId
        }
        key = os.getenv(const.jwtKey) or const.defaultKey
        encodeJwt = jwt.encode(payload, key, algorithm='HS256')

        return encodeJwt

    def deToken(token):
        data = None
        secret = os.getenv(const.jwtKey) or const.defaultKey
        try:
            data = jwt.decode(token, secret, algorithms=['HS256'])
        except Exception as e:
            print(e)
        # if not data is None:
        #     session = Session()
        #     if session.query(exists().where(Token.token==token)).scalar():
        #         return None
        return data

    def verifyToken(token):
        data = JWT.deToken(token)
        if data is None:
            return False
        return True
